<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Cache;
use think\Config;
/**
 * 答题接口📝
 */
class Subj extends Api
{
    // protected $noNeedLogin = ['get_subj'];
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];




    // protected $handler = null;

    // protected $options = [
    //     'host'       => '127.0.0.1',
    //     'port'       => 6379,
    //     'password'   => '',
    //     'select'     => 0,
    //     'timeout'    => 0,
    //     'expire'     => 0,
    //     'persistent' => false,
    //     'prefix'     => '',
    // ];

    // /**
    //  * 构造函数
    //  * @param array $options 缓存参数
    //  * @access public
    //  */
    // public function __construct($options = [])
    // {
    //     if(!extension_loaded('redis')) {
    //         $this->error("请检查redis扩展是否已添加");
    //     }

    //     // 获取 redis 配置
    //     $config = \think\Config::get('redis');
        
        
    //     //优先使用框架的配置
    //     if(!empty($config)) {
    //         $this->options = array_merge($this->options, $config);
    //     }
    //     if(!empty($options)) {
    //         $this->options = array_merge($this->options, $options);
    //     }
    //     $this->handler = new \Redis();
    //     if($this->options['persistent']) {
    //         $this->handler->pconnect($this->options['host'], $this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']);
    //     } else {
    //         $this->handler->connect($this->options['host'], $this->options['port'], $this->options['timeout']);
    //     }

    //     if('' != $this->options['password']) {
    //         $this->handler->auth($this->options['password']);
    //     }

    //     if(0 != $this->options['select']) {
    //         $this->handler->select($this->options['select']);
    //     }

    //     // if(empty($config) && empty($options)) {
    //     //     $this->error('请检查config.php里是否有redis配置，或addons\redisgeo\Redis.php里配置');
    //     // } 

    //     // 赋值全局，避免多次实例化
    //     $GLOBALS['REDIS'] = $this->handler;
    // }

    // public function getRedis() {
    //     return $this->handler;
    // }






    /**
     * 获取题目（5天）
     *
     * @param integer $limit 数量默认1
     * @return void
     */
    public function get_subj($limit=1)
    {
        // $this->redis = $this->getRedis();
        // $this->redis
        // $list_ids = Db::name('subj')->column('id');
        // halt($list_ids);

        // $data = DB::name('subj')->where('id','>',0)->select();
        // $data = DB::name('subj')->select();

        if($this->today($this->auth->id)){  //  今天回答没有

            $get_poster = $this->get_poster($this->auth->id);//创建一张海报

            $this->error('今天回答完成!',$get_poster,3);
        }
        
        $data = Cache::get('all_subj');
        if(!$data){
            Cache::set('all_subj',DB::name('subj')->where('subj_status','1')->field('answer,subj_status,createtime',true)->select(),600);
            $data = Cache::get('all_subj');
        }

        
        
        // $data = Cache::get('all_subj');
        if($limit==1){
            $new_data =$data[array_rand($data,$limit)];
        }else{
            $ids = array_rand($data,$limit);
            $new_data = array();
            foreach($ids as $key => $val){
                $new_data[] = $data[$val];
            }
        }
        

        
       
        $this->success('ok',$new_data);
    }






    /**
     * 验证答案
     */
    public function verify_the_answer($id,$answer)
    {
        $subj = Db::name('subj')->find($id);
        if(!$subj){
            $this->error('没有此题');
        }

        if($answer==$subj['answer']){
            return true;
        }else{
            return false;
        }
    }


    /**
     * 提交答案（单题）
     *
     * @param string $id 题目id
     * @param string $answer 答案内容
     * @return void
     */
    public function submit_answers($id,$answer)
    {   
        if($this->verify_the_answer($id,$answer)){
            //存储答题 
            $data['user_id'] = $this->auth->id;
            $data['subj_id'] = $id;
            $data['answer'] = $answer;
            $data['time'] = time();
            $data['date'] = date('Y_m_d');
            
            Db::name('submit_subj')->insertGetId($data);

            $key = date('Y_m_d').'_user'.$this->auth->id;
            $data = Cache::tag('submit_subj')->set($key,$id);
            

            // if(strtotime(Config::get('site.hot_time'))<time()){
            //     $this->error('活动时间已过');
            // }
            $get_poster = $this->get_poster($this->auth->id);//创建一张海报

            $this->success('回答正确',$get_poster,3);
        }else{
            $this->error('需要再接再厉');
        }
    }



    /**
     * 今天是否答题正确了
     *
     * @param [type] $user_id
     * @return void
     */
    protected function today($user_id)
    {
        $key = date('Y_m_d').'_user'.$user_id;
        $data = Cache::get($key);
        if(!$data){
            return false;
        }else{
            return true;
        }
        
    }

    /**
     * 获取海报
     *
     * @param [type] $user_id
     * @return void
     */
    protected function get_poster($user_id){
        // $name = date('Y_m_d').'_user'.$user_id;
        $key = date('Y_m_d').'_image';
        $data = Cache::get($key);
        if(!$data){
            
            Cache::set($key,Db::name('image')->where('date',date('Y_m_d'))->value('image'),120);
            $data = Cache::get($key);
        }
        return $data;
    }
    


    /**
     * 测试接口获取今天海报地址
     *
     * @param Type $var
     * @return void
     */
    public function test_image()
    {
        echo $this->get_poster(1);
    }


    

}
